package se.peterbjorkman.android.trafikkamera;

import se.peterbjorkman.android.trafikkamera.providers.CameraContentProvider;
import se.peterbjorkman.android.trafikkamera.providers.CameraDefs;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class RoutesCameraActivity extends CameraTreeActivity {

	private static final int CONTEXTMENU_DELETE_ID =  Menu.FIRST;
	private static final int CONTEXTMENU_SHOWALL =  CONTEXTMENU_DELETE_ID + 1;
	private static final int CONTEXTMENU_RENAME =  CONTEXTMENU_SHOWALL + 1;
	private static final int CONTEXTMENU_DELETE =  CONTEXTMENU_RENAME + 1;
	
	private static final int DIALOG_RENAME_ROUTE = 1;

	private static final int ADD_MENU_ID = MainActivity.LAAT_USED_MENUID + 1;
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Toast.makeText(this, "Långtryck på rutt för valet att visa alla dess kameror samtidigt.", Toast.LENGTH_LONG).show();
    }
    
	@Override
    protected String[] getRootNames() {
		return new String[] { CameraDefs.NAME};
	}

    @Override
	protected int[] getRootViesIds() {
		return new int[] { android.R.id.text1 };
	}
	
	@Override
	protected int getRootLayout() {
		return android.R.layout.simple_expandable_list_item_1;
	}

	@Override
	protected Cursor getRootCursor() {
		String[] projection = new String[] { 
				CameraDefs.ID, 
				CameraDefs.NAME}; //TODO Cameradef

		return managedQuery(
				CameraContentProvider.ROUTES_URI,
				projection, null, null, CameraDefs.NAME);
	}
	
	@Override
	protected String getChildFilter(Cursor rootCursor) {
		long id = rootCursor.getLong(rootCursor.getColumnIndexOrThrow(CameraDefs.ID));
		// TODO hardcoded sql
		return "EXISTS (SELECT 1 from camerasinroutes cir where cir.cameraid = cameras._id AND cir.routeId = " + id + ")";
	}
	
	@Override
	protected String getChildOrder() {
		return null; // TODO  order by sortorder somehow
	}
	
	@Override
	protected void onCreateContextMenuChild(ContextMenu menu, long groupId, long id){
		super.onCreateContextMenuChild(menu, groupId, id);
		menu.add(ContextMenu.NONE, CONTEXTMENU_DELETE_ID, ContextMenu.NONE, getString(R.string.RemoveFromRoute));
	}
	
	@Override
    protected View getEmptyView(){
    	TextView view = new TextView(this);
    	view.setText(R.string.NoRoutesInfo);
    	return view;
    }
	
	protected boolean onContextItemSelectedChild(int itemId, long groupId, long childId) {
		if (itemId == CONTEXTMENU_DELETE_ID){
			deleteCameraFromRoute(groupId, childId);
			return true;
		}
		return super.onContextItemSelectedChild(itemId, groupId, childId);
	}

	private void deleteCameraFromRoute(long routeId, long cameraId) {		
		ContentResolver cr = getContentResolver();

		String filter = "cameraid = " + cameraId + " AND routeid = " + routeId; 
				
        cr.delete(CameraContentProvider.CAMERAROUTES_URI, filter, null);
	}
	
	private void deleteRoute(long routeId) {		
		ContentResolver cr = getContentResolver();

		String filter = "routeid = " + routeId; 
				
        cr.delete(CameraContentProvider.CAMERAROUTES_URI, filter, null);
        filter = CameraDefs.ID + " = " + routeId; 
        cr.delete(CameraContentProvider.ROUTES_URI, filter, null);
        Toast.makeText(this, "Rutten raderad. (P.g.a. bugg försvinnner rutten först när applikationen startas om.)", Toast.LENGTH_LONG).show();
	}
	
	@Override
	protected void onCreateContextMenuGroup(ContextMenu menu, long id){
		super.onCreateContextMenuGroup(menu, id);
		menu.add(ContextMenu.NONE, CONTEXTMENU_SHOWALL, ContextMenu.NONE, getString(R.string.ShowAll));
		menu.add(ContextMenu.NONE, CONTEXTMENU_RENAME,  ContextMenu.NONE, getString(R.string.Rename));
		menu.add(ContextMenu.NONE, CONTEXTMENU_DELETE,  ContextMenu.NONE, getString(R.string.DeleteRoute));
	}

	@Override
	protected boolean onContextItemSelectedGroup(int itemId, long id, int groupPosition) {
		if (itemId == CONTEXTMENU_SHOWALL){ // TODO use switch
			Intent i = new Intent(this, CameraGalleryActivity.class);
			i.putExtra(CameraGalleryActivity.INTENT_EXTRA_ROUTEID, id);
			startActivity(i);
			return true;
		} else if (itemId == CONTEXTMENU_RENAME){
			renameRoute(id, groupPosition);
			return true;
		} else if (itemId == CONTEXTMENU_DELETE){
			deleteRoute(id);
			return true;
		}
		return super.onContextItemSelectedGroup(itemId, id, groupPosition);
	}

	// Ugly hack showDialog does not take a bundle until API ver 8
	private long mLastId;
	private String mLastName;

	private void renameRoute(long id, int groupPosition) {
		Cursor cursor = getGroupCursor(groupPosition);
		mLastName = cursor.getString(cursor.getColumnIndexOrThrow(CameraDefs.NAME));
		mLastId = id;
		showDialog(DIALOG_RENAME_ROUTE);
	}
 
	@Override
	protected Dialog onCreateDialog(int dialogId) {
		switch (dialogId) {
		case DIALOG_RENAME_ROUTE: {
			// TODO Get from bundle
			final long routeId = mLastId;
			String name = mLastName;
			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setTitle(R.string.RenamRouteDialogTitle);
			alert.setIcon(android.R.drawable.ic_menu_edit);

			alert.setMessage(R.string.RenamRouteDialogMessage);

			// Set an EditText view to get user input
			final EditText input = new EditText(this);
			input.setText(name);
			alert.setView(input);

			alert.setPositiveButton(R.string.Ok,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							 String newName = input.getText().toString();
							 updateRouteName(routeId, newName);
						}
					});

			alert.setNegativeButton(R.string.Canccel, null);

			return alert.create();
		}
		}
		return null;
	}

	protected void updateRouteName(long routeId, String value) {
		ContentResolver cr = getContentResolver();

		ContentValues values = new ContentValues();
		values.put(CameraDefs.NAME, value);
        cr.update(CameraContentProvider.ROUTES_URI, values, CameraDefs.ID + " = " + routeId, null);
	}

	@Override
	    public boolean onCreateOptionsMenu(Menu menu) {
	        //Log.d(LOGTAG, "In onCreateOptionsMenu");
	        
	        super.onCreateOptionsMenu(menu);

	        menu.add(0, ADD_MENU_ID, 0, getString(R.string.NewRoute))
	            ;//.setIcon(R.drawable.menu_update);
	        return true;
	    }
	    
	    @Override
	    public boolean onOptionsItemSelected(MenuItem item) {
	        //Log.d(LOGTAG, "In onOptionsItemSelected");
	     
	        switch (item.getItemId()) {
	        case ADD_MENU_ID:
	        	HandleCreateNewRoute();
	            return true;
	        }
	    
	        return super.onOptionsItemSelected(item);
	    }

		private void HandleCreateNewRoute() {
			ContentResolver cr = getContentResolver();

			ContentValues values = new ContentValues();
			values.put(CameraDefs.NAME, getString(R.string.NewRouteName));
	        cr.insert(CameraContentProvider.ROUTES_URI,values);
		}

		public static boolean routeExists(Context context) {
			String[] projection = new String[] {"count(*)"};

			ContentResolver cr = context.getContentResolver();

			Cursor cur = cr.query(
					CameraContentProvider.ROUTES_URI,
					projection, null, null, CameraDefs.NAME)
					;
			cur.moveToFirst();
			int numberOfRoutes = cur.getInt(0);
			cur.close();
			return (numberOfRoutes > 0);
		}
}
